const {
  NAME_OR_PASSWORD_IS_REQUIRED,
  NAME_IS_NOT_EXISTS,
  PASSWORD_ERROR,
  UNAUTHORIZATION,
} = require("../constant");
const md5password = require("../utils/md5password");
const userService = require("../service/user.server");
const { publicKey } = require("../config/keys");
const jwt = require("jsonwebtoken");

const verifyLogin = async (ctx, next) => {
  try {
    const { name, password } = ctx.request.body;
    //1.判断用户和密码是否为空
    if (!name || !password) {
      return ctx.app.emit("error", NAME_OR_PASSWORD_IS_REQUIRED, ctx);
    }
    //2.查询该用户是否在数据库中存在

    const user = await userService.findUserByName(name);
    const currentUser = user[0];

    if (!currentUser) {
      return ctx.app.emit("error", NAME_IS_NOT_EXISTS, ctx);
    }

    //3.查询数据库中密码和用户传递的密码是否一致
    const verifyPassword = md5password(password);
    if (verifyPassword !== currentUser.password) {
      return ctx.app.emit("error", PASSWORD_ERROR, ctx);
    }

    //把数据库中查到的id name 传给下个中间件
    ctx.user = currentUser;
    await next();
  } catch (error) {
    console.log(error, "login.middleware错误");
  }
};

//验证请求头是否携带token,token是否伪造
const verifyAuth = async (ctx, next) => {
  console.log("验证授权的middleware~");
  // 1.获取token
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    return ctx.app.emit("error", UNAUTHORIZATION, ctx);
  }
  const token = authorization.replace("Bearer ", "");

  // 2.验证token(id/name/iat/exp)
  try {
    const result = jwt.verify(token, publicKey, {
      algorithms: ["RS256"],
    });
    ctx.user = result;
    await next();
  } catch (err) {
    ctx.app.emit("error", UNAUTHORIZATION, ctx);
  }
};

module.exports = { verifyLogin, verifyAuth };
